package com.bckj.fastboot.core.mybatisplus;

import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.type.TypeHandlerRegistry;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
import java.util.regex.Matcher;

public class MSUtils {


    public static String getTableName(MappedStatement ms) {
        try {
            // 获取Mapper接口全限定名
            String mapperClassName = ms.getId().substring(0, ms.getId().lastIndexOf("."));
            Class<?> mapperClass = Class.forName(mapperClassName);

            // 获取实体类类型
            Class<?> entityClass = getEntityClassFromMapper(mapperClass);

            if (entityClass == null) {
                return null;
            }

            // 获取表名注解
            TableName tableNameAnnotation = entityClass.getAnnotation(TableName.class);
            if (tableNameAnnotation != null) {
                return tableNameAnnotation.value();
            }

            // 默认表名（类名转下划线）
            return StringUtils.camelToUnderline(entityClass.getSimpleName());
        } catch (Exception e) {
            return null;
        }
    }

    public static Class<?> getEntityClassFromMapper(Class<?> mapperClass) {
        // 通过MyBatis-Plus的BaseMapper泛型参数获取实体类
        Type[] genericInterfaces = mapperClass.getGenericInterfaces();
        for (Type genericInterface : genericInterfaces) {
            if (genericInterface instanceof ParameterizedType parameterizedType) {
                if (parameterizedType.getRawType().equals(BaseMapper.class)) {
                    Type entityType = parameterizedType.getActualTypeArguments()[0];
                    return (Class<?>) entityType;
                }
            }
        }
       return null;
    }

    public static String getMethodName(MappedStatement ms) {
        String id = ms.getId();
        // 格式通常为: "com.example.mapper.UserMapper.selectById"
        return id.substring(id.lastIndexOf(".") + 1);
    }

    public static String getCompleteSql(MappedStatement ms, Object parameterObject) {
        Configuration configuration = ms.getConfiguration();
        BoundSql boundSql = ms.getBoundSql(parameterObject);
        String sql = boundSql.getSql();
        // 获取参数映射
        List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
        if (sql == null || sql.isEmpty()) {
            return "";
        }

        if (parameterMappings.isEmpty() || parameterObject == null) {
            return sql;
        }

        TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();
        StringBuilder sqlBuilder = new StringBuilder(sql);

        MetaObject metaObject = null;
        if (!typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
            metaObject = configuration.newMetaObject(parameterObject);
        }

        // 从后往前替换，避免替换后索引位置变化
        for (int i = parameterMappings.size() - 1; i >= 0; i--) {
            ParameterMapping parameterMapping = parameterMappings.get(i);
            String propertyName = parameterMapping.getProperty();

            Object value;
            // 复杂对象，通过MetaObject获取属性值
            if (metaObject != null) {
                value = metaObject.getValue(propertyName);
            } else {
                value = parameterObject;
            }

            // 处理参数值，添加引号等
            String valueStr = getParameterValue(value);

            // 替换?为实际值
            Matcher matcher = java.util.regex.Pattern.compile("\\?").matcher(sqlBuilder);
            int count = 0;
            while (matcher.find()) {
                count++;
                if (count == i + 1) {
                    sqlBuilder.replace(matcher.start(), matcher.end(), valueStr);
                    break;
                }
            }
        }

        return sqlBuilder.toString();
    }

    /**
     * 处理参数值，根据类型添加引号
     */
    private static String getParameterValue(Object value) {
        String strValue;
        if (value instanceof Number) {
            strValue = value.toString();
        } else if (value instanceof Boolean) {
            strValue = ((Boolean) value) ? "1" : "0";
        } else {
            strValue = "'" + value + "'";
        }
        return strValue;
    }

}
